#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
from urllib.parse import unquote

import scrapy
import re

from lxml import etree

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, base64, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanYnsrmzf0150Policy(BaseTaxPolicySpider):
    name = 'yunnan_ynwlt_policy'

    source = '云南省文化和旅游厅'
    province = '云南省'
    city = ''
    county = ''
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                "DOWNLOADER_MIDDLEWARES": {
                    # "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        url = "https://dct.yn.gov.cn/listajax.aspx?"
        params = {
            "PageSize": "20",
            "TempletName": "classlist_xxgk.html",
            "orderField": "CreatTime",
            "": "",
            "id": "330055897825",
            "page": "1"
        }
        meta = {"params": params, "url": url}
        yield scrapy.Request(url + urllib.parse.urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='news_text']/div//a[contains(@href, 'htm') or @title]/ancestor::div[string-length(string(.))>=10]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath(""".//span/text()""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # print(item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath(""".""").re_first(r"""1\s+/\s+(\d+)""")
            print(total_page)
            for page_num in range(2, int(total_page) + 1):
                params = meta['params']
                params['page'] = page_num
                url = meta['url']
                yield response.follow(url + urllib.parse.urlencode(params), callback=self.parse_list,
                                      meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item['publish_date'] or response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("""string(//meta[@name='pubdate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_ynwlt_policy".split())
